package xyz.riceball.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.riceball.beans.BeanDefinition;
import xyz.riceball.exception.BeanDefinitionRegistryException;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/6/29 19:57
 */
public class PreBuildBeanFactory extends DefaultBeanFactory {

    private final Logger log = LoggerFactory.getLogger(getClass());
    /**
     * 存放bean的名字
     */
    private final List<String> beanNames = new ArrayList<>();

    public List<String> getBeanNames() {
        return beanNames;
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionRegistryException {
        super.registerBeanDefinition(beanName, beanDefinition);
        synchronized (beanNames) {
            beanNames.add(beanName);
        }
    }

    /**
     * 创建单例bean实例
     *
     * @throws Exception 。
     */
    public void preInstantiateSingletons() throws Exception {
        synchronized (beanNames) {
            for (String name : beanNames) {
                BeanDefinition bd = this.getBeanDefinition(name);
                this.doGetBean(name);
                if (log.isDebugEnabled()) {
                    log.debug("preInstantiate: name=" + name + " " + bd);
                }
            }
        }
    }
}
